<template>
  <div
    class="avatar"
    :style="`width: ${imgWidth}px; padding-bottom: ${imgWidth}px;`"
  >
    <img
      :src="imgUri"
      :alt="alt"
      class="avatar-img"
      @error="loadError"
    >
  </div>
</template>

<script>
export default {
  name: 'Avatar',
  props: {
    imgWidth: {
      type: Number,
      default: 40
    },
    avatarUri: {
      type: String,
      default: ''
    },
    alt: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      publicPath: process.env.BASE_URL,
      imgUri: ''
    }
  },
  watch: {
    avatarUri: {
      handler(newVal) {
        this.imgUri = newVal
      },
      deep: true
    }
  },
  mounted() {
    this.imgUri = this._.isNil(this.avatarUri) ? `${this.publicPath}static/avatar.jpg` : this.avatarUri
  },
  methods: {
    loadError() {
      this.imgUri = `${this.publicPath}static/avatar.jpg`
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar {
  position: relative;
  border-radius: 6px;
  overflow: hidden;
  .avatar-img {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 1;
    height: 100%;
  }
}
</style>
